package com.hello.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.hello.system.service.IEmailService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * 邮件服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements IEmailService {

    private final JavaMailSender mailSender;

    @Value("${spring.mail.username:}")
    private String fromEmail;

    /**
     * 发送简单文本邮件
     *
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    @Override
    public void sendEmail(String to, String subject, String content) {
        log.info("=== 开始发送文本邮件 ===");
        log.info("发件人: {}, 收件人: {}, 主题: {}", fromEmail, to, subject);
        
        if (!validateEmail(to)) {
            log.error("收件人邮箱格式不正确: {}", to);
            throw new IllegalArgumentException("收件人邮箱格式不正确: " + to);
        }

        if (fromEmail == null || fromEmail.isEmpty()) {
            log.error("发件人邮箱未配置，请检查application-mail.yml中的spring.mail.username配置");
            throw new IllegalStateException("发件人邮箱未配置，请检查application-mail.yml中的spring.mail.username配置");
        }

        try {
            log.info("创建邮件对象...");
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            message.setSentDate(new Date());
            
            log.info("邮件内容准备完成，开始发送...");
            mailSender.send(message);
            log.info("邮件发送指令已执行，成功发送邮件至: {}", to);
        } catch (Exception e) {
            log.error("邮件发送失败: {}", e.getMessage(), e);
            log.error("邮件配置信息: 发件人={}", fromEmail);
            throw new RuntimeException("邮件发送失败: " + e.getMessage(), e);
        }
        log.info("=== 邮件发送流程结束 ===");
    }

    /**
     * 发送HTML格式邮件
     *
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param htmlContent HTML格式的邮件内容
     */
    @Override
    public void sendHtmlEmail(String to, String subject, String htmlContent) {
        log.info("=== 开始发送HTML邮件 ===");
        log.info("发件人: {}, 收件人: {}, 主题: {}", fromEmail, to, subject);
        
        if (!validateEmail(to)) {
            log.error("收件人邮箱格式不正确: {}", to);
            throw new IllegalArgumentException("收件人邮箱格式不正确: " + to);
        }
        
        if (fromEmail == null || fromEmail.isEmpty()) {
            log.error("发件人邮箱未配置，请检查application-mail.yml中的spring.mail.username配置");
            throw new IllegalStateException("发件人邮箱未配置，请检查application-mail.yml中的spring.mail.username配置");
        }

        try {
            log.info("创建MIME邮件对象...");
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            helper.setSentDate(new Date());
            
            log.info("HTML邮件内容准备完成，开始发送...");
            mailSender.send(message);
            log.info("HTML邮件发送指令已执行，成功发送邮件至: {}", to);
        } catch (MessagingException e) {
            log.error("HTML邮件发送失败: {}", e.getMessage(), e);
            log.error("邮件配置信息: 发件人={}", fromEmail);
            throw new RuntimeException("HTML邮件发送失败: " + e.getMessage(), e);
        }
        log.info("=== HTML邮件发送流程结束 ===");
    }

    /**
     * 简单校验邮箱格式
     *
     * @param email 邮箱地址
     * @return 是否有效
     */
    private boolean validateEmail(String email) {
        boolean isValid = StringUtils.hasText(email) && email.matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$");
        if (!isValid) {
            log.warn("邮箱格式验证失败: {}", email);
        }
        return isValid;
    }
} 